<?php
session_start();
require_once("_connect.php");
if(count($_GET)>0)
{
	$billcode = $_GET["Search"];
	$max = $_GET["Max"];
	$min = $_GET["Min"];
	if($billcode != "" && $max != "" && $min != "" )
	{
		echo lookupBillcodeMsg($conn, $billcode, $max, $min);	
	}	
}

function lookupBillcodeMsg($conn, $billcode, $max, $min)
{
	$sql = "SELECT *   
			FROM billcodemsg msg WHERE 
			msg.billcode =".$billcode." AND
			(msg.camp BETWEEN ".$min." AND ".$max.") AND 
			msg.active = 'YES'";
			//echo $sql;
	$raw = mysql_query($sql, $conn);
	$row = mysql_fetch_array($raw, MYSQL_ASSOC);
	if (is_array($row))
	{
		return $row["message"];
	}
	else
	{
		return lookupBillcode($conn, $billcode, $max, $min);
	}	
}

function lookupBillcode($conn, $billcode, $max, $min)
{
    $rows = $_SESSION['ORDER_DETAIL'];
    $exists_id = BillCodeExists($billcode, $rows);
    //print_r($exists_id);
    if (is_array($exists_id))
    {
    	//print_r($exists_id);
		$Duplicate = "รหัสสั่งซื้อซ้ำ!!! ลำดับที่ ".$exists_id['LISTNO']." ".$exists_id['BILLCODE']." ".$exists_id['BILLDESC']." จำนวน ".$exists_id['QTY']." ชิ้น";		
	}

	$sql = "SELECT *   
			FROM billcode bill WHERE 
			bill.billcode =".$billcode." AND
			(bill.camp BETWEEN ".$min." AND ".$max.")";
			//echo $sql;
	$raw = mysql_query($sql, $conn);
	$row = mysql_fetch_array($raw, MYSQL_ASSOC);
	if (is_array($row))
	{
		return $row["BILLCODE"]."|".$row["BILLDESC"]."|".$row["PRICE"]."|".$row["CAMP"]."|".$Duplicate;
	}
	else
	{
		return "Notfound";
	}			

}

function BillCodeExists($billcode, $array)
{
	if (is_array($array))
	{
		foreach ($array AS $rowNum => $row)
		{
			$tmp = array();
			if ($billcode == $row['BILLCODE']) {
				$tmp = $array[$rowNum];
				$tmp["LISTNO"] = $rowNum;
				return $tmp;
			}
		}			
	}
	return 0;
}
?>